import { useTokenStore } from '@/stores/token';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const baseURL = '/api';
const instance = axios.create({ baseURL });

const noTokenPatterns = ['/auth/login', '/auth/register', '/auth/send-email-code'];

instance.interceptors.request.use(
  config => {
    const tokenStore = useTokenStore();
    const needAuth = config.url && !noTokenPatterns.some(path => config.url?.includes(path));
    if (needAuth && tokenStore.token) {
      config.headers.Authorization = tokenStore.token;
    }
    return config;
  },
  err => {
    ElMessage.error('请求拦截器发生错误');
    return Promise.reject(err);
  }
);

// ✅ 响应拦截器：只返回 res.data.data，简化调用
instance.interceptors.response.use(
  res => {
    if (res.data.status === 0) {
      return res.data; 
    }
    ElMessage(res.data.msg ?? '操作失败');
    return Promise.reject(res.data);
  },
  err => {
    if (err.response?.status === 401) {
      ElMessage.error('请先登录');
    } else {
      ElMessage.error('服务异常');
    }
    return Promise.reject(err);
  }
);

export default instance;

